using System;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Media.Effects;
using Microsoft.Win32;
using Hardcodet.Wpf.TaskbarNotification;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace WaistGuard
{
    public partial class MainWindow : Window
    {
        private DispatcherTimer? workTimer;
        private DispatcherTimer? displayTimer;
        private DateTime startTime;
        private RestWindow? restWindow;
        private bool isResting = false;
        private TaskbarIcon? notifyIcon;

        private int workDuration = 45;
        private int breakDuration = 5;
        private bool autoStart = false;
        private bool isPreResting = false;

        public MainWindow()
        {
            InitializeComponent();
            InitializeTimers();
            LoadSettings();
            
            // 直接设置字体大小
            WorkTimeLabel.FontSize = 24;
            WorkTimeLabel.FontFamily = new FontFamily("Microsoft YaHei");
            
            this.Closing += MainWindow_Closing;
            InitializeTrayIcon();
        }

        private void InitializeTimers()
        {
            startTime = DateTime.Now;
            
            workTimer = new DispatcherTimer();
            workTimer.Interval = TimeSpan.FromMinutes(workDuration);
            workTimer.Tick += WorkTimer_Tick;
            workTimer.Start();

            displayTimer = new DispatcherTimer();
            displayTimer.Interval = TimeSpan.FromSeconds(1);
            displayTimer.Tick += DisplayTimer_Tick;
            displayTimer.Start();
        }

        private void WorkTimer_Tick(object? sender, EventArgs e)
        {
            if (!isResting)
            {
                var elapsed = DateTime.Now - startTime;
                var totalMinutes = workDuration;
                var remainingSeconds = (totalMinutes * 60) - elapsed.TotalSeconds;

                if (remainingSeconds <= 30 && !isPreResting)
                {
                    ShowPreRestWindow();
                }
                else if (remainingSeconds <= 0)
                {
                    ShowRestWindow();
                }
            }
        }

        private void DisplayTimer_Tick(object? sender, EventArgs e)
        {
            var elapsed = DateTime.Now - startTime;
            var minutes = Math.Max(0, elapsed.Minutes);
            var seconds = Math.Max(0, elapsed.Seconds);
            WorkTimeLabel.Content = $"已工作时长：{minutes}分钟:{seconds}秒";
        }

        private void ShowRestWindow()
        {
            isResting = true;
            workTimer?.Stop();
            
            restWindow = new RestWindow(breakDuration);
            restWindow.RestCompleted += RestWindow_RestCompleted;
            restWindow.Show();
        }

        private void RestWindow_RestCompleted(object? sender, EventArgs e)
        {
            isResting = false;
            startTime = DateTime.Now;
            workTimer?.Start();
            restWindow = null;
        }

        private void LoadSettings()
        {
            using (var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"))
            {
                autoStart = key?.GetValue("WaistGuard") != null;
            }
        }

        private void RestartTimer_Click(object sender, RoutedEventArgs e)
        {
            // 重置所有状态
            startTime = DateTime.Now;
            isResting = false;
            isPreResting = false;
            
            // 停止并重启工作计时器
            workTimer?.Stop();
            workTimer?.Start();
            
            // 停止并重启显示计时器
            displayTimer?.Stop();
            displayTimer?.Start();
            
            // 关闭所有可能打开的窗口
            if (restWindow != null)
            {
                restWindow.Close();
                restWindow = null;
            }
        }

        private void About_Click(object sender, RoutedEventArgs e)
        {
            var aboutWindow = new Window
            {
                Title = "关于",
                Width = 450,
                Height = 350,
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                WindowStyle = WindowStyle.None,
                AllowsTransparency = true,
                Background = Brushes.White,
                BorderThickness = new Thickness(1),
                BorderBrush = new SolidColorBrush(Color.FromRgb(225, 225, 225))
            };

            var mainGrid = new Grid();

            // 添加阴影效果
            var shadowEffect = new DropShadowEffect
            {
                BlurRadius = 10,
                ShadowDepth = 0,
                Opacity = 0.2,
                Color = Colors.Black
            };

            var border = new Border
            {
                CornerRadius = new CornerRadius(8),
                Effect = shadowEffect
            };

            var contentGrid = new Grid();

            // 标题栏
            var titleBar = new Grid { Height = 32, VerticalAlignment = VerticalAlignment.Top, Background = Brushes.Transparent };
            titleBar.MouseLeftButtonDown += (s, args) => 
            {
                if (args.LeftButton == MouseButtonState.Pressed)
                {
                    aboutWindow.DragMove();
                }
            };

            var titleText = new TextBlock
            {
                Text = "关于",
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(12, 0, 0, 0)
            };

            var closeButton = new Button
            {
                Content = "✕",
                Width = 46,
                Height = 32,
                HorizontalAlignment = HorizontalAlignment.Right,
                Style = Application.Current.Resources["CloseButtonStyle"] as Style  // 使用全局定义的关闭按钮样式
            };
            closeButton.Click += (s, args) => aboutWindow.Close();

            titleBar.Children.Add(titleText);
            titleBar.Children.Add(closeButton);

            // 内容区域
            var contentPanel = new StackPanel { Margin = new Thickness(20, 32, 20, 20) };

            var aboutText = new TextBlock
            {
                Text = "护腰使者 v1.0\n\n为您的健康保驾护航！\n\nPowered by 程序员七平\n\n联系方式：扫码关注微信公众号：",
                TextWrapping = TextWrapping.Wrap,
                TextAlignment = TextAlignment.Center,
                Margin = new Thickness(0, 0, 0, 20),
                FontSize = 14
            };
            contentPanel.Children.Add(aboutText);

            // 添加二维码图片
            try
            {
                var qrCodeImage = new Image
                {
                    Source = new BitmapImage(new Uri("pack://application:,,,/Resources/qrcode_for_weyoung.jpg", UriKind.Absolute)),
                    Width = 120,
                    Height = 120,
                    HorizontalAlignment = HorizontalAlignment.Center
                };
                contentPanel.Children.Add(qrCodeImage);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载二维码图片失败: {ex.Message}", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
            }

            contentGrid.Children.Add(titleBar);
            contentGrid.Children.Add(contentPanel);
            border.Child = contentGrid;
            mainGrid.Children.Add(border);
            aboutWindow.Content = mainGrid;

            aboutWindow.ShowDialog();
        }

        private Style CreateCloseButtonStyle()
        {
            var style = new Style(typeof(Button));
            var template = new ControlTemplate(typeof(Button));
            var border = new FrameworkElementFactory(typeof(Border));
            border.SetValue(Border.BackgroundProperty, new TemplateBindingExtension(BackgroundProperty));
            
            var contentPresenter = new FrameworkElementFactory(typeof(ContentPresenter));
            contentPresenter.SetValue(HorizontalAlignmentProperty, HorizontalAlignment.Center);
            contentPresenter.SetValue(VerticalAlignmentProperty, VerticalAlignment.Center);
            
            border.AppendChild(contentPresenter);
            template.VisualTree = border;

            var mouseOverTrigger = new Trigger { Property = IsMouseOverProperty, Value = true };
            mouseOverTrigger.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Color.FromRgb(236, 65, 65))));
            mouseOverTrigger.Setters.Add(new Setter(ForegroundProperty, Brushes.White));

            var pressedTrigger = new Trigger { Property = Button.IsPressedProperty, Value = true };
            pressedTrigger.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Color.FromRgb(215, 53, 53))));
            pressedTrigger.Setters.Add(new Setter(ForegroundProperty, Brushes.White));

            style.Triggers.Add(mouseOverTrigger);
            style.Triggers.Add(pressedTrigger);
            style.Setters.Add(new Setter(TemplateProperty, template));

            return style;
        }

        private void Exit_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void MainWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        private void InitializeTrayIcon()
        {
            try
            {
                notifyIcon = new TaskbarIcon();
                var iconPath = "pack://application:,,,/Resources/icon.ico";
                notifyIcon.IconSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(iconPath));
                
                // 添加双命令
                notifyIcon.DoubleClickCommand = new RelayCommand(() => {
                    this.Show();
                    this.WindowState = WindowState.Normal;
                    this.Activate();
                });

                // 设置托盘图标的菜单
                var contextMenu = new System.Windows.Controls.ContextMenu();
                contextMenu.Background = Brushes.White;

                // 修改菜单项样式
                var menuItemStyle = new Style(typeof(MenuItem));
                menuItemStyle.Setters.Add(new Setter(MenuItem.BackgroundProperty, Brushes.White));
                menuItemStyle.Setters.Add(new Setter(MenuItem.ForegroundProperty, Brushes.Black));
                menuItemStyle.Setters.Add(new Setter(MenuItem.PaddingProperty, new Thickness(10, 5, 10, 5)));
                menuItemStyle.Setters.Add(new Setter(MenuItem.MarginProperty, new Thickness(0)));
                menuItemStyle.Setters.Add(new Setter(MenuItem.BorderThicknessProperty, new Thickness(0)));
                menuItemStyle.Setters.Add(new Setter(MenuItem.IconProperty, null));  // 移除图标

                // 添加鼠标悬停效果
                var trigger = new Trigger { Property = IsMouseOverProperty, Value = true };
                trigger.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Color.FromRgb(230, 230, 230))));
                menuItemStyle.Triggers.Add(trigger);

                contextMenu.Items.Add(new MenuItem 
                { 
                    Header = "显示主窗口",
                    Command = new RelayCommand(() => {
                        this.Show();
                        this.WindowState = WindowState.Normal;
                        this.Activate();
                    }),
                    Style = Application.Current.Resources["MenuItemStyle"] as Style
                });
                contextMenu.Items.Add(new MenuItem 
                { 
                    Header = "立即休息",
                    Command = new RelayCommand(() => ShowPreRestWindow(true)),
                    Style = Application.Current.Resources["MenuItemStyle"] as Style
                });
                contextMenu.Items.Add(new MenuItem 
                { 
                    Header = "重新计时",
                    Command = new RelayCommand(() => RestartTimer_Click(null, null)),
                    Style = Application.Current.Resources["MenuItemStyle"] as Style
                });
                contextMenu.Items.Add(new MenuItem 
                { 
                    Header = "设置",
                    Command = new RelayCommand(ShowSettings),
                    Style = Application.Current.Resources["MenuItemStyle"] as Style
                });
                contextMenu.Items.Add(new MenuItem 
                { 
                    Header = "关于",
                    Command = new RelayCommand(() => About_Click(null, null)),
                    Style = Application.Current.Resources["MenuItemStyle"] as Style
                });
                contextMenu.Items.Add(new MenuItem 
                { 
                    Header = "退出",
                    Command = new RelayCommand(() => Exit_Click(null, null)),
                    Style = Application.Current.Resources["MenuItemStyle"] as Style
                });

                notifyIcon.ContextMenu = contextMenu;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化托盘图标失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ShowSettings()
        {
            var settingsWindow = new Window
            {
                Title = "设置",
                Width = 650,
                Height = 500,
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                WindowStyle = WindowStyle.None,
                AllowsTransparency = true,
                Background = Brushes.White,
                BorderThickness = new Thickness(1),
                BorderBrush = new SolidColorBrush(Color.FromRgb(225, 225, 225))
            };

            var mainGrid = new Grid();
            mainGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });  // 添加标题栏行
            mainGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
            mainGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

            // 添加标题栏
            var titleBar = new Grid { Height = 32, Background = Brushes.Transparent };
            titleBar.MouseLeftButtonDown += (s, args) => 
            {
                if (args.LeftButton == MouseButtonState.Pressed)
                {
                    settingsWindow.DragMove();
                }
            };

            var titleText = new TextBlock
            {
                Text = "设置",
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(12, 0, 0, 0)
            };

            var closeButton = new Button
            {
                Content = "✕",
                Width = 46,
                Height = 32,
                HorizontalAlignment = HorizontalAlignment.Right,
                Style = Application.Current.Resources["CloseButtonStyle"] as Style
            };
            closeButton.Click += (s, args) => settingsWindow.Close();

            titleBar.Children.Add(titleText);
            titleBar.Children.Add(closeButton);
            Grid.SetRow(titleBar, 0);
            mainGrid.Children.Add(titleBar);

            // 内容区域
            var contentGrid = new Grid { Margin = new Thickness(20, 5, 20, 5) };
            contentGrid.RowDefinitions.Clear();  // 清除现有的行定义
            contentGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });  // 基本设置标题
            contentGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });  // 工作时长
            contentGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });  // 休息时长
            contentGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });  // 机自启动
            contentGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });  // 提示信息标题
            contentGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });  // 提示信息文本框

            // 添加列定义
            contentGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(120) });  // 固定宽度的标签列
            contentGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });  // 自适应宽度的内容列

            // 分组：基本设置
            var basicSettingsHeader = new TextBlock 
            { 
                Text = "基本设置",
                FontSize = 16,
                FontWeight = FontWeights.Bold,
                Margin = new Thickness(0, 0, 0, 10)
            };
            Grid.SetRow(basicSettingsHeader, 0);
            Grid.SetColumn(basicSettingsHeader, 0);
            Grid.SetColumnSpan(basicSettingsHeader, 2);
            contentGrid.Children.Add(basicSettingsHeader);

            // 工作时长设置
            var workLabel = new Label 
            { 
                Content = "工作时长(分钟):", 
                HorizontalAlignment = HorizontalAlignment.Right,
                Style = Application.Current.Resources["CommonLabel"] as Style
            };
            Grid.SetRow(workLabel, 1);
            Grid.SetColumn(workLabel, 0);
            contentGrid.Children.Add(workLabel);

            var workTextBox = new TextBox 
            { 
                Text = workDuration.ToString(), 
                Width = 100,
                Height = 30,
                Margin = new Thickness(5),
                VerticalContentAlignment = VerticalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Left,
                Cursor = Cursors.IBeam
            };
            Grid.SetRow(workTextBox, 1);
            Grid.SetColumn(workTextBox, 1);
            contentGrid.Children.Add(workTextBox);

            // 休息时长设置
            var breakLabel = new Label 
            { 
                Content = "休息时长(分钟):", 
                HorizontalAlignment = HorizontalAlignment.Right,
                Style = Application.Current.Resources["CommonLabel"] as Style
            };
            Grid.SetRow(breakLabel, 2);
            Grid.SetColumn(breakLabel, 0);
            contentGrid.Children.Add(breakLabel);

            var breakTextBox = new TextBox 
            { 
                Text = breakDuration.ToString(), 
                Width = 100,
                Height = 30,
                Margin = new Thickness(5),
                VerticalContentAlignment = VerticalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Left,
                Cursor = Cursors.IBeam
            };
            Grid.SetRow(breakTextBox, 2);
            Grid.SetColumn(breakTextBox, 1);
            contentGrid.Children.Add(breakTextBox);

            // 开机自启动设置
            var autoStartLabel = new Label 
            { 
                Content = "开机自启动:", 
                HorizontalAlignment = HorizontalAlignment.Right,
                Style = Application.Current.Resources["CommonLabel"] as Style
            };
            Grid.SetRow(autoStartLabel, 3);
            Grid.SetColumn(autoStartLabel, 0);
            contentGrid.Children.Add(autoStartLabel);

            var autoStartToggle = new ToggleButton 
            { 
                IsChecked = autoStart,
                Width = 40,
                Height = 24,
                Margin = new Thickness(5),
                Style = CreateToggleButtonStyle(),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Center,
                Cursor = Cursors.Hand
            };
            Grid.SetRow(autoStartToggle, 3);
            Grid.SetColumn(autoStartToggle, 1);
            contentGrid.Children.Add(autoStartToggle);

            // 在基本设置域添加二维码图片和提示文字
            try
            {
                var qrCodePanel = new StackPanel
                {
                    HorizontalAlignment = HorizontalAlignment.Right,
                    VerticalAlignment = VerticalAlignment.Top,
                    Margin = new Thickness(150, 0, 20, 0)
                };

                var qrCodeText = new TextBlock
                {
                    Text = "微信扫一扫关注我",
                    HorizontalAlignment = HorizontalAlignment.Center,
                    Margin = new Thickness(0, 10, 0, 10),
                    FontSize = 12
                };
                qrCodePanel.Children.Add(qrCodeText);

                var qrCodeImage = new Image
                {
                    Source = new BitmapImage(new Uri("pack://application:,,,/Resources/qrcode_for_weyoung.jpg", UriKind.Absolute)),
                    Width = 120,
                    Height = 120
                };
                qrCodePanel.Children.Add(qrCodeImage);

                Grid.SetRow(qrCodePanel, 0);
                Grid.SetColumn(qrCodePanel, 1);
                Grid.SetRowSpan(qrCodePanel, 4);
                Panel.SetZIndex(qrCodePanel, -1);
                contentGrid.Children.Add(qrCodePanel);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载二维码图片失败: {ex.Message}", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
            }

            // 分组：提示信息
            var tipsHeader = new TextBlock 
            { 
                Text = "休息提示语",
                FontSize = 16,
                FontWeight = FontWeights.Bold,
                Margin = new Thickness(0, 5, 0, 5)
            };
            Grid.SetRow(tipsHeader, 4);  // 放在第5行
            Grid.SetColumn(tipsHeader, 0);
            Grid.SetColumnSpan(tipsHeader, 2);
            contentGrid.Children.Add(tipsHeader);

            // 提示信息文框
            var tipsTextBox = new TextBox 
            { 
                Text = string.Join("\n\n", RestWindow.DefaultTips),
                Margin = new Thickness(5, 5, 5, 0),
                TextWrapping = TextWrapping.Wrap,
                AcceptsReturn = true,
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                Height = 200, 
                MaxHeight = 200,
                Cursor = Cursors.IBeam
            };
            Grid.SetRow(tipsTextBox, 5);  // 放在第6行
            Grid.SetColumn(tipsTextBox, 0);
            Grid.SetColumnSpan(tipsTextBox, 2);
            contentGrid.Children.Add(tipsTextBox);

            Grid.SetRow(contentGrid, 1);
            mainGrid.Children.Add(contentGrid);

            // 底部按区域
            var buttonPanel = new StackPanel 
            { 
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Right,
                Margin = new Thickness(20, 10, 20, 20)
            };

            var saveButton = new Button 
            { 
                Content = "保存",
                Width = 80,
                Height = 30,
                Margin = new Thickness(0, 0, 10, 0),
                Style = Application.Current.Resources["NormalButtonStyle"] as Style,  // 使用普通按钮样式
                Cursor = Cursors.Hand
            };
            saveButton.Click += (s, e) => 
            {
                // 保存设置
                if (int.TryParse(workTextBox.Text, out int newWorkDuration))
                {
                    workDuration = newWorkDuration;
                    if (workTimer != null)
                    {
                        workTimer.Interval = TimeSpan.FromMinutes(workDuration);
                    }
                }
                if (int.TryParse(breakTextBox.Text, out int newBreakDuration))
                {
                    breakDuration = newBreakDuration;
                }

                if (autoStart != autoStartToggle.IsChecked)
                {
                    autoStart = autoStartToggle.IsChecked == true;
                    using (var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true))
                    {
                        if (autoStart)
                        {
                            key?.SetValue("WaistGuard", System.Reflection.Assembly.GetExecutingAssembly().Location);
                        }
                        else
                        {
                            key?.DeleteValue("WaistGuard", false);
                        }
                    }
                }

                RestWindow.DefaultTips = tipsTextBox.Text.Split(new[] { "\r\n\r\n", "\n\n" }, StringSplitOptions.RemoveEmptyEntries);
                settingsWindow.Close();
            };
            buttonPanel.Children.Add(saveButton);

            var cancelButton = new Button 
            { 
                Content = "取消",
                Width = 80,
                Height = 30,
                Style = Application.Current.Resources["NormalButtonStyle"] as Style,  // 使用普通按钮样式
                Cursor = Cursors.Hand
            };
            cancelButton.Click += (s, e) => settingsWindow.Close();
            buttonPanel.Children.Add(cancelButton);

            Grid.SetRow(buttonPanel, 2);
            mainGrid.Children.Add(buttonPanel);

            settingsWindow.Content = mainGrid;
            settingsWindow.ShowDialog();
        }

        private Style CreateToggleButtonStyle()
        {
            var style = new Style(typeof(ToggleButton));

            // 创建背景画刷
            var uncheckedBrush = new SolidColorBrush(Color.FromRgb(200, 200, 200));
            var checkedBrush = new SolidColorBrush(Color.FromRgb(0, 120, 215));

            // 创建圆形按钮模板
            var template = new ControlTemplate(typeof(ToggleButton));
            var border = new FrameworkElementFactory(typeof(Border));
            border.SetValue(Border.CornerRadiusProperty, new CornerRadius(10));
            border.SetValue(Border.BackgroundProperty, new TemplateBindingExtension(BackgroundProperty));

            var ellipse = new FrameworkElementFactory(typeof(Ellipse));
            ellipse.SetValue(Ellipse.FillProperty, Brushes.White);
            ellipse.SetValue(Ellipse.WidthProperty, 16.0);
            ellipse.SetValue(Ellipse.HeightProperty, 16.0);
            ellipse.SetValue(Ellipse.MarginProperty, new Thickness(2));
            ellipse.SetValue(HorizontalAlignmentProperty, HorizontalAlignment.Left);

            border.AppendChild(ellipse);
            template.VisualTree = border;

            // 添加触发器
            var checkedTrigger = new Trigger { Property = ToggleButton.IsCheckedProperty, Value = true };
            checkedTrigger.Setters.Add(new Setter(BackgroundProperty, checkedBrush));
            checkedTrigger.Setters.Add(new Setter(Border.BackgroundProperty, checkedBrush));
            checkedTrigger.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Right));

            var uncheckedTrigger = new Trigger { Property = ToggleButton.IsCheckedProperty, Value = false };
            uncheckedTrigger.Setters.Add(new Setter(BackgroundProperty, uncheckedBrush));
            uncheckedTrigger.Setters.Add(new Setter(Border.BackgroundProperty, uncheckedBrush));
            uncheckedTrigger.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Left));

            style.Triggers.Add(checkedTrigger);
            style.Triggers.Add(uncheckedTrigger);
            style.Setters.Add(new Setter(TemplateProperty, template));

            return style;
        }

        private void DragWindow(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        private void CloseWindow(object sender, RoutedEventArgs e)
        {
            this.Hide();
        }

        private void ShowPreRestWindow(bool isManual = false)
        {
            isPreResting = true;
            var preRestWindow = new PreRestWindow(isManual);
            preRestWindow.Closed += (s, args) =>
            {
                if (!preRestWindow.IsDelayed)  // 不是延迟，��示休息窗口
                {
                    ShowRestWindow();
                }
                else  // 是延迟，启动3分钟计时器
                {
                    var delayTimer = new DispatcherTimer
                    {
                        Interval = TimeSpan.FromMinutes(3)
                    };
                    delayTimer.Tick += (sender, e) =>
                    {
                        delayTimer.Stop();
                        isPreResting = false;  // 重置标志，允许显示预休息窗口
                        ShowPreRestWindow(false);  // 3分钟后重新显示预休息窗口
                    };
                    delayTimer.Start();
                }
            };
            preRestWindow.Show();
        }
    }

    // 添加一个简单的命令实现
    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Func<object, bool> _canExecute;

        public RelayCommand(Action execute)
            : this(_ => execute(), null)
        {
        }

        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
} 